/*********************************************************************************
 *      Copyright:  (C) 2022 Zhang Changxing<ZhangChangxingVIP@163.com>
 *                  All rights reserved.
 *
 *       Filename:  my_thread.c
 *    Description:  This file is mainly used to create multithreads
 *                 
 *        Version:  1.0.0(07/28/2022)
 *         Author:  Zhang Changxing <ZhangChangxingVIP@163.com>
 *      ChangeLog:  1, Release initial version on "07/28/2022  01:33:25 AM"
 *                 
 ********************************************************************************/


#include "my_thread.h"

void *thread_worker1(void *args);
void *thread_worker2(void *args);


/*-----------------------------------------------------------------------------
 *   description:   Create multiple threads, including both for 
 *                  MQTT connection and SMS sending and receiving
 *          args:   $iotd_ctx:    The context address used to create multithreads
 *  return value:   <0: failure,    =0:ok 
 *----------------------------------------------------------------------------*/
int mqtt_thread(iotd_ctx_t *iotd_ctx)
{
    pthread_t tid;
    pthread_attr_t thread_attr;

    
    if( pthread_attr_init(&thread_attr) )
    {
        printf("pthread_attr_init() failure: %s\n", strerror(errno));
        return -1;
    }


    if( pthread_attr_setstacksize(&thread_attr, 120*1024) )
    {
        printf("pthread_attr_setstacksize() failure: %s\n", strerror(errno));
        return -2;
    }


    if( pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED) )
    {
        printf("pthread_attr_setdetachstate() failure: %s\n", strerror(errno));
        return -1;
    }

    if(0 != pthread_create(&tid, &thread_attr, thread_worker1, iotd_ctx))
    {
        printf("Failed to create thread1!\n");
    }
    printf("Thread worker1 tid[%ld] created ok\n", tid);

    if(0 != pthread_create(&tid, &thread_attr, thread_worker2, iotd_ctx))
    {
        printf("Failed to create thread2!\n");
    }
    printf("Thread worker2 tid[%ld] created ok\n", tid);

    pthread_attr_destroy(&thread_attr);
    

}

//Thread 1, MQTT sends and receives data, failed to send data stored in the database
void *thread_worker1(void *args)
{
    int     rv = -1;
    int     start_time = 0;
    float   thre_value = 30;
    float   temper = 0;
    char    sms_buf[64]= {0};
    char    phone_buf[64] = "+8618628067132";
    char    target_number[64] = {0};

    iotd_ctx_t *iotd_ctx = (iotd_ctx_t *)args;
    pub_ctx_t   *pub_ctx = &(iotd_ctx->pub_ctx);
    ttyusb_ctx_t *ttyusb_ctx = &(iotd_ctx->ttyusb_ctx);
    thread_ctx_t    *thread_ctx = &(iotd_ctx->thread_ctx);


    while(1)
    {
        if(iotd_ctx->pack_info.samp_falg)
        {
            pack_to_cjson(pub_ctx, iotd_ctx->pack_info);
            temper = iotd_ctx->pack_info.temper;
            if(temper >= thread_ctx->thre_value)
            {
                thread_ctx->tty_flag = 1;
            }

            if(0 == pub_ctx->connect_flag)
            {
                db_data_insert(iotd_ctx->pack_info);
                iotd_ctx->pack_info.samp_falg = 0;
                continue;
            }

            log_info("------------------------------------Sending sampling data------------------------------------\n");
            pub_ctx->pub_flag = 0;
            rv = publish_data(pub_ctx);
            start_time = getime(NULL);
            do{

            }while((pub_ctx->pub_flag == 0) && ((getime(NULL) - start_time) < 2));
            if(( rv < 0) || (pub_ctx->pub_flag == 0))
            {
                db_data_insert(iotd_ctx->pack_info);
                pub_ctx->connect_flag = 0;
            }
            else
            {
                log_info("Publish sample data sucessfully:temperature= %f\n", iotd_ctx->pack_info.temper);
            }
            iotd_ctx->pack_info.samp_falg = 0;
            
        }

        if(check_table_data() && (1 == pub_ctx->connect_flag))
        {
            log_info("------------------------------------Sending database data------------------------------------\n");
            select_first_data(&(iotd_ctx->pack_info));
            pack_to_cjson(pub_ctx, iotd_ctx->pack_info);
            
            pub_ctx->pub_flag = 0;
            rv = publish_data(pub_ctx);
            start_time = getime(NULL);
            do{

            }while((pub_ctx->pub_flag == 0) && ((getime(NULL) - start_time) < 2));

            if( (rv < 0) || (pub_ctx->pub_flag == 0))
            {
                pub_ctx->connect_flag = 0;
                continue;
            }

            db_data_delete();
            log_info("Publish database data sucessfully:temperature= %f\n", iotd_ctx->pack_info.temper);
        }

    }
    
}

//Thread 2, SMS sending and receiving, switching cloud platforms and resetting temperature thresholds
void *thread_worker2(void *args)
{
    int     rv = -1;
    int     start_time = 0;
    float   temper = 0;
    char    return_buf[1024]= {0};
    char    phone_buf[64] = "+8618628067132";
    char    target_number[64] = "8618628067132";
    char    target_number1[64] = {0};
    char    *start_ptr = NULL;
    int     platform;

    iotd_ctx_t      *iotd_ctx = (iotd_ctx_t *)args;
    pub_ctx_t       *pub_ctx = &(iotd_ctx->pub_ctx);
    ttyusb_ctx_t    *ttyusb_ctx = &(iotd_ctx->ttyusb_ctx);
    thread_ctx_t    *thread_ctx = &(iotd_ctx->thread_ctx);
#if 1
    while(1)
    {

        if(thread_ctx->tty_flag)
        {
            temper = iotd_ctx->pack_info.temper;
            printf("temper = %f\n", temper);
            printf("thre_value = %f\n", thread_ctx->thre_value);
            printf("温度过高！\n");
            memset(target_number1, 0, sizeof(target_number1));
            snprintf(target_number1, strlen(phone_buf) + 1, "%s", phone_buf);
            memset(return_buf, 0 , sizeof(return_buf));
            snprintf(return_buf, strlen("注意！温度过高:") + sizeof(temper) + 1,"注意！温度过高:%f", temper);
            send_pdu_sms(ttyusb_ctx, target_number1, return_buf);
            thread_ctx->tty_flag = 0;
        }

        memset(return_buf, 0, sizeof(return_buf));
        rv = listen_index0(ttyusb_ctx, return_buf, sizeof(return_buf), target_number);
        if(return_buf)
        {
            if(start_ptr = strstr(return_buf, "打开继电器"))
            {
                printf("打开继电器\n");
                continue;
            }

            if(start_ptr = strstr(return_buf, "设置温度阈值为"))
            {
                printf("设置温度阈值\n");
                start_ptr = start_ptr + strlen("设置温度阈值为");
                thread_ctx->thre_value = atof(start_ptr);
                printf("新的温度阈值为：%f\n", thread_ctx->thre_value);
                start_ptr = NULL;
                continue;
            }

            if(start_ptr = strstr(return_buf, "选择云平台为"))
            {
                printf("选择云平台\n");
                start_ptr = start_ptr + strlen("选择云平台为");
                if(strstr(start_ptr, "阿里云"))
                {
                    choose_platform(iotd_ctx, 0);
                }
                else if(strstr(start_ptr, "腾讯云"))
                {
                    choose_platform(iotd_ctx, 1);
                }
                else if(strstr(start_ptr, "华为云"))
                {
                    choose_platform(iotd_ctx, 2);
                }
                
                mqtt_init(iotd_ctx);
                printf("切换云平台成功\n");

                continue;
            }
        }
    }
#endif
}












